﻿using System;
using System.Collections.Generic;
using System.Text;
using Engine.Components.Workers;
using Engine.Components.Interface;

namespace Engine.Components
{
    public class Hunter: Interface.IHunter
    {
        #region MEMBERS
        HunterPluginSDK.Interface.IProgressHandler _ph;
        DataSchema.CollectionSchema _cs;
        #endregion

        #region FACTORY
        private Hunter(HunterPluginSDK.Interface.IProgressHandler ph, DataSchema.CollectionSchema cs)
        {
            _ph = ph;
            _cs = cs;
        }

        static public IHunter CreateInstance(HunterPluginSDK.Interface.IProgressHandler ph, DataSchema.CollectionSchema cs)
        {
            return new Hunter(ph, cs);
        }

        #endregion

        #region PRIVATE
        IWorker CreateDirectoryScanner()
        {
            if (_cs == null)
            {
                if (_ph != null)
                    _ph.WriteToOutput("Hunter.No data source", HunterPluginSDK.LogPriority.CRITICAL);
                throw new Exception("Hunter.No data source");
            }
            Job job = Engine.Components.Workers.Job.CreateFirstJob();
            foreach (string dir in _cs.GetSelectedIncomingFolders())
            {
                job.Queue.Enqueue(dir);
            }
            IWorker ds1 = Engine.Components.Workers.DirectoryScanner.CreateWorker(_ph);
            ds1.InputTasks = job;
            return ds1;
        }

        IWorker CreateFileInfoProducer(IWorker ds)
        {
            IWorker ds2 = Engine.Components.Workers.FileInfoProducer.CreateWorker(_ph);
            ds2.InputTasks = ds.OutputTasks;
            return ds2;
        }

        IWorker CreateFileOperation(IWorker ds)
        {
            IWorker ds2 = Engine.Components.Workers.FileOperation.CreateWorker(_ph, _cs);
            ds2.InputTasks = ds.OutputTasks;
            return ds2;
        }

        IWorker CreateFileMatcher(IWorker ds)
        {
            IWorker ds2 = Engine.Components.Workers.FileMatcher.CreateWorker(_ph, _cs);
            ds2.InputTasks = ds.OutputTasks;
            return ds2;
        }


        #endregion

        #region IHunter Members

        void Interface.IHunter.Hunt()
        {
            DateTime now = DateTime.Now;

            IWorker ds = CreateDirectoryScanner();
            IWorker fip = CreateFileInfoProducer(ds);
            IWorker fm = CreateFileMatcher(fip);
            IWorker fo = CreateFileOperation(fm);

            DateTime now1 = DateTime.Now;
            TimeSpan ts = now1 - now;
            _ph.WriteToOutput("Hunting lasts " + ts.ToString(), HunterPluginSDK.LogPriority.INFO);

        }

        #endregion
    }
}
